import * as mobx from 'mobx';
import {observable, action, computed, asMap} from 'mobx';
import {WeaForm} from 'comsMobx';
import * as API from '../apis/api';
import findIndex from 'lodash/findIndex';
import concat from 'lodash/concat';
import dropWhile from 'lodash/dropWhile';
import formLogListStore from './formLogListStore';
import * as Api from '../apis/communication';
import isFunction from 'lodash/isFunction';
import cloneDeep from 'lodash/cloneDeep';
import { toJS } from 'mobx';
export default class WfCenterLogListStore  {

    @observable loading = false;
    @observable submitLoading = false;
    @observable logList = [];
    logCount = 0;
    @observable logParams = {};
    submitParams = {};
    commonParams = {};
    @observable variableMap = observable.map ? observable.map({}) : asMap({});    //变量属性
    @observable rightMenu = {};
    @observable logItemBaseParams = {};
    @observable appStatus = {};
    constructor() {
        this.init = this.init;
        this.loadMarkInfo = this.loadMarkInfo;
        this.setLogData = this.setLogData;
        this.controlVariableMap = this.controlVariableMap;
        this.updateLogParams = this.updateLogParams;
        this.loadMore = this.loadMore;
        this.loadFormRigthMunu = this.loadFormRigthMunu;
        this.clearDatas = this.clearDatas;
        this.reloadLogList = this.reloadLogList;
        this.doSubmit = this.doSubmit;
        this.updateReqInfo = this.updateReqInfo;
    }
 
     @observable communicateSettingKey = {
        isShowSignCommunicate: '1',
        isExpendCommunicate: '1', 
     }
    @action
    init = (initLogParams = {}, visible = false) =>  {
        this.loading = true;
        initLogParams.loadmethod = 'portal';
        API.getReqBaseParams(initLogParams).then((data = {}) => {
            const {submitParams = {}, logBaseParams = {}, params = {}} = data;
            const {verifyRight = false} = params;

            const baseParamKey = ["requestid", "requestType", "workflowid", "nodeid", "signatureAttributesStr", "signatureSecretKey", "f_weaver_belongto_userid",
                "f_weaver_belongto_usertype", "authStr", "authSignatureStr", "isprint", "required", "requestname", "requestnamenew", "isHideArea","beagenter",
                "isurger"
              ];

            const rightParamKey = ['viewLogIds', 'creatorNodeId', 'isHideInput', 'orderbytype', 'logpagesize', 'loadmethod'];
            let commonParams = {};

            const communicateKey = ['isShowSignCommunicate', 'isExpendCommunicate', 'isOpenCommunication'];
            //督办参数
            const {urger = ''} = initLogParams;
            commonParams.urger = urger;

            baseParamKey.map(v => {
                commonParams[v] = params[v];
            });

            submitParams['signatureAttributesStr'] = params['signatureAttributesStr'];
            submitParams['signatureSecretKey'] = params['signatureSecretKey'];

            const logParams = {};
            logParams['submit'] = params.requestType;
            logParams['pgnumber'] = 1;
            logParams['maxrequestlogid'] = 0;

            rightParamKey.map(v => {
                logParams[v] = logBaseParams[v] || '';
            })
            communicateKey.map( v => {
              if(logBaseParams[v]) {
                this.communicateSettingKey[v] = logBaseParams[v];
              }
              if(v == 'isOpenCommunication') {
                commonParams[v] = params[v]; //相关交流功能开启与否参数
              }
            })
            logParams['wfsignlddtcnt'] = 4;
            this.submitParams = submitParams;
            this.commonParams = commonParams;
            this.logItemBaseParams = commonParams;
            this.logParams = {...commonParams, ...logParams};
            if (verifyRight) {
                this.loadMarkInfo();
                this.loadFormRigthMunu();
            } else {
                this.loading = false;
            }
            this.updateReqInfo();
            this.getAppStatus(this.commonParams);
        })
        this.controlVariableMap('visible', visible);
    }

    @action
    loadMarkInfo = () =>  {
        if (!this.loading) this.loading = true;
        API.getRequestLogList(this.logParams).then(data => {
            const {loglist = [], maxrequestlogid, totalCount} = data;
            const _loglist = concat(mobx.toJS(this.logList), loglist);
            this.logParams = {...this.logParams, maxrequestlogid};
            this.setLogData(_loglist, totalCount);
            this.getComment(); 
            this.loading = false;
        });
    }

    @action('更新请求参数')
    updateLogParams = (params = {}, isLoadLog = false) =>  {
        this.logParams = {...this.logParams, ...params};
        if (isLoadLog) {
            this.loadMarkInfo();
        }
    }

    loadMore = () =>  {
        const {pgnumber = 1, maxrequestlogid = 0} = this.logParams;
        this.updateLogParams({pgnumber: parseInt(pgnumber) + 1, maxrequestlogid: maxrequestlogid}, true);
    }

    @action
    setLogData = (logList, logCount) =>  {
        this.logCount = logCount;
        this.logList = logList;
    }

    @action('控制变量区')
    controlVariableMap = (key, value)  => {
        this.variableMap.set(key, value);
    }

    @action
    loadFormRigthMunu = () =>  {
        API.getRightMenu(this.commonParams).then(data => {
            const {forward = ''} = data;
            this.commonParams['forward'] =  forward;
            data.rightMenus.sort((o1, o2) => {
                return o1.order - o2.order;
            });
            this.rightMenu = data;
        })
    }

    clearDatas = () =>  {
        this.setLogData([], 0);
        this.updateLogParams({pgnumber: 1, maxrequestlogid: 0});
    }

    reloadLogList = () =>  {
        this.clearDatas();
        this.loadMarkInfo();
    }

    doSubmit = (remark = '', onCancel) =>  {
        const otherParams = mobx.toJS(this.variableMap.get('submitParam'));
        const {requestid = -1} = this.submitParams;
        this.submitLoading = true;
        API.wfCenterSubmit({
            ...this.submitParams, ...otherParams,
            remark,
            'multiSubIds': requestid
        }).then((data = {}) => {
            //回调
            this.controlVariableMap('showSubmitDialog', false);
            this.controlVariableMap('visible', false);
            // try {
            //     jQuery('#btnWfCenterReload').trigger('click');
            // } catch (e) {
            // }
            this.clearDatas();
            this.rightMenu = {};
            this.commonParams = {};
            this.submitLoading = false;
            try{
                typeof onCancel === 'function' && onCancel(true);
            }catch (e) {}
        });
    }

    @observable hasSubmitRight = false;
    @action('获取富文本相关底部设置项')
    getAppStatus = (params={}) => {
        Api.getInitParams(params).then(data => {
            this.appStatus = data.appStatus;
            this.hasSubmitRight = data.hasSubmitRight;
        })
    }
    @action('加载签字意见评论内容')
    getComment = (params) => {
      this.logList.map( (v,index) => {
        let passParams = {...this.commonParams, type: 'list', requestLogId: v.logid};
        if(v.hasCommunicationQuote) {
          Api.getContentList(passParams).then( data => {
            const { contentList } = data;
            this.logList[index] = {...v, commentList: contentList};
          })
        }
      });
    }
 

    @action('保存被回复人的签字意见文本') 
    setReplyMark = (text) => {
      this.signReplyText = text;
    }
    @action('保存一级回复')
    saveReplyOthers = (params, callBack) => {
      const { replyInfo={}, richParams } = params;
      let passParams = {};
      let str = '';
      if(richParams.remark != '') {
        str = richParams.remark.replace(/<\/?[^>]*>/g, '');
        str = str.replace(/[\u200B-\u200D\uFEFF]/g, "");
        str = str.replace(/\n/g,'');
        str = str.replace("&#8203;", "").replace(/&nbsp;/g, '');
        str = str.trim();
      } 
      if (!str) {
        message.destroy();
        message.error(getLabel(382648, '请输入交流内容'));
        return false;
      }
      let newParams = { "reply_man": replyInfo.displayname, 
                        "log_useid": replyInfo.displayid,
                        "log_displaydepid": replyInfo.displaydepid,
                        "log_displaydepname": replyInfo.displaydepname,
                        "log_operatedate": replyInfo.log_operatedate,
                        "log_operatetime": replyInfo.log_operatetime,
                        "log_nodename": replyInfo.log_nodename,
                        "operationname": replyInfo.operationname,
                        "sign_logid": replyInfo.logid,
                        "signReplyText":  this.signReplyText,
                        'log_userType': replyInfo.displaytype == '0' ? '1' : replyInfo.displaytype == '1' ? '2' : ''
                      }
      passParams = { ...newParams, ...richParams,...this.logParams, "quote_type": 'quoteSign'};
      Api.doSaveContent(passParams).then(res => {
        if(res.result) {
          // this.reflashContentList(replyInfo.logid);
          this.reloadLogList();
        }
        isFunction(callBack) && callBack();
      })
    }

    //删除评论
    delContent = (params,id) => {
      Api.doDelete({...this.logParams,...params}).then(data => {
        if(data.canDelete === false) {
            message.destroy();
            message.error(getLabel('512478','已超过规定时间或有新内容，无法删除'));
        } else {
          this.reflashContentList(id);
        }
      })
    }
   
  /**
     * 编辑交流内容
     */
    editContent = (params,logid, callBack) => {
      Api.doEditContent({...this.baseParam,...params}).then(data => {
          if(data.canModify === false){
              message.destroy();
              message.error("已超过规定时间或有新内容，无法编辑！");
          }
          this.reflashContentList(logid);
          isFunction(callBack) && callBack();
      })
  }

  @action('刷新评论内容')
  reflashContentList = (id) => {
    let passParams = {type: 'list', requestLogId: id, ...this.logParams};
    Api.getContentList(passParams).then( data => {
      let tempArr = cloneDeep(toJS(this.logList));
      tempArr.map( (v,index) => {
        if(v.logid == id) {
          tempArr[index].commentList = [...data.contentList];
        }})
      this.logList = tempArr;
    })
        
        
  }

    updateReqInfo = () => {
        const { requestid,iscreate,nodetype,wfmonitor,urger ,nodeid} = this.commonParams;
        API.updateReqInfo({
            requestid: requestid,
            currentnodetype: nodetype,
            wfmonitor: wfmonitor,
            isurger: urger=='1',
            nodeid
        }).then(data=>{
          
        });
    }
}